package legumes.client.services.util.rpc;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public abstract class AbstractAsyncHandler<T> implements AsyncCallback<T> {

	private Throwable throwable = null;

	public void onFailure(Throwable caught_) {
		setThrowable(caught_);
		Window.alert(caught_.getMessage());
	}

	protected void setThrowable(Throwable throwable_) {
		throwable = throwable_;
	}

	public boolean hasSucceed() {
		return getThrowable() == null;
	}

	public boolean hasFailed() {
		return getThrowable() != null;
	}

	public Throwable getThrowable() {
		return throwable;
	}

	public String getMessages(Throwable t_) {
		StringBuilder sb = new StringBuilder();

		Throwable t = t_;

		while (t != null) {

			sb.append(t.getClass().getName()).append(" ")
					.append(t.getMessage()).append("<br>");

			t = t_.getCause();
		}

		return sb.toString();
	}

	public abstract void onSuccess(T result);
}